import chatApi from '../../../services/chat/chat';
import dateUtil from '../../../services/_utils/date';
import WebSocketService from '../../../services/websocket/websocket.js';
import {
  upload
} from '../../../services/_utils/request';

var msgPage = 1,
  _self;
const event = require('../../../services/websocket/event.js');
Page({
  data: {
    bottomViewId: 0,
    scrollHeight: 0,
    inputValue: '',
    keyboardHeight: 0,
    groupId: null,
    toUserId: null,
    currentUserId: getApp().globalData.userInfo.userId,
    messages: []
  },
  onLoad: function (options) {
    this.setData({
      toUserId: options.userId
    })
    if (options.groupId == null && options.userId) { // 需要创建会话组
      console.log(options.userId)
      let group = {
        ownerId: getApp().globalData.userInfo.userId,
        members: [getApp().globalData.userInfo.userId, options.userId]
      }
      chatApi.createGroup(group).then(res => {
        console.log(res)
        this.getMessageList(res.groupId);
      })
    } else {
      this.getMessageList(options.groupId);
    }

    // 订阅 WebSocket 消息事件
    event.on('websocketMessage', this.handleWebSocketMessage);
  },
  onShow() {
    const wsService = new WebSocketService();
    wsService.reConnect(getApp().globalData.userInfo.userId);
    getApp().globalData.wsService = wsService

    //this.moveScrollButtom()
  },

  createGroup(toUserId) {
    return new Promise((resolve, reject) => {
      getApp().globalData.wsService.createGroup(toUserId)
      resolve();
    });
  },


  getMessageList(groupId) {
    var that = this
    chatApi.getMessageList(groupId).then(res => {
      console.log(res)
      let messages = []
      res.forEach(o => {
        messages.push(that.convertMsg(o))
      })
      that.setData({
        messages: messages,
        groupId: groupId
      })
      that.moveScrollButtom()
    })
  },

  convertMsg(msg) {
    let message = {
      id: msg.fromUser,
      name: msg.fromUserName,
      face: msg.fromUserAvatarUrl,
      msg: msg.content,
      ctype: msg.type == 'txt' ? 1 : 2, // 消息类型 [ 1. 文本类型 2. 图片类型 3. 语音类型 4. 系统通知 ]
      date: dateUtil.formatDateTime(msg.createTime)
    }
    return message;
  },

  onUnload: function () {
    // 取消订阅，避免内存泄漏
    event.off('websocketMessage', this.handleWebSocketMessage);
  },
  handleWebSocketMessage: function (message) {
    // 处理接收到的 WebSocket 消息
    var that = this
    let groupId = that.data.groupId
    if (message.groupId == groupId) {
      let messages = that.data.messages
      console.log(that.convertMsg(message))
      messages.push(that.convertMsg(message))
      that.setData({
        messages: messages
      })
      that.moveScrollButtom()
    }
  },

  // 下拉加载历史
  onPullDownRefresh: function () {},

  // 发送文本消息
  sendTextMsg: function () {
    let content = this.data.inputValue
    if (content.trim() == '') {
      return
    }
    const messge = {
      from: this.data.currentUserId,
      to: this.data.toUserId,
      groupId: this.data.groupId,
      content: content,
      action: 'chat',
      type: 'txt'
    }
    getApp().globalData.wsService.send(messge)
    this.setData({
      inputValue: ''
    });
  },
  // 发送图片消息
  sendImgMsg: function (e) {
    var that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        console.log(res.tempFiles[0].tempFilePath)
        upload(res.tempFiles[0].tempFilePath).then(data => {
          console.log(data)
          const messge = {
            from: that.data.currentUserId,
            to: that.data.toUserId,
            groupId: that.data.groupId,
            content: data,
            action: 'chat',
            type: 'img'
          }
          getApp().globalData.wsService.send(messge)
        });
      }
    })

    var imgUrl = e.detail;
    // 此处已经获取到选择的临时图片，上传图片[ 与服务器交互完成 ]
    // 服务器会回复一个消息到当前链接
    // 模拟接收到一个消息
    var msg = {
      id: 1000, //用户id
      name: "graceUI 网友", // 昵称
      face: "https://graceui.oss-cn-beijing.aliyuncs.com/faces/2.png", // 用户头像
      msg: imgUrl, // 图片文件路径
      ctype: 2, // 消息类型 [ 1. 文本类型 2. 图片类型 3. 语音类型 4. 系统通知 ]
      date: this.getNowDate()
    }
  },
  // 获取当前日期
  getNowDate: function () {
    var date = new Date();
    var sign1 = "-";
    var sign2 = ":";
    var year = date.getFullYear() // 年
    var month = date.getMonth() + 1; // 月
    var day = date.getDate(); // 日
    var hour = date.getHours(); // 时
    var minutes = date.getMinutes(); // 分
    var seconds = date.getSeconds() //秒
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (day >= 0 && day <= 9) {
      day = "0" + day;
    }
    if (hour >= 0 && hour <= 9) {
      hour = "0" + hour;
    }
    if (minutes >= 0 && minutes <= 9) {
      minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
      seconds = "0" + seconds;
    }
    var currentdate = year + sign1 + month + sign1 + day + " " + hour + sign2 + minutes + sign2 + seconds;
    return currentdate;
  },
  onFocus: function (e) {
    // 监听键盘高度变化
    wx.onKeyboardHeightChange(res => {
      console.log("res.height", res.height)
      this.setData({
        keyboardHeight: res.height // 更新键盘高度
      });
    });
  },

  onBlur: function (e) {
    // 当输入框失去焦点时，取消监听键盘高度变化
    wx.offKeyboardHeightChange(res => {
      this.setData({
        keyboardHeight: 0 // 更新键盘高度
      });
    });
  },
  onInput: function (e) {
    // 更新输入框的值
    this.setData({
      inputValue: e.detail.value
    });
  },
  onConfirm: function () {
    const inputValue = this.data.inputValue;
    if (inputValue.trim() !== '') {
      this.sendTextMsg();
    }
  },

  moveScrollButtom() {
    let length = this.data.messages.length
    console.log("length", length)
    this.setData({
      bottomViewId: 'item-' + (length - 1)
    });
    console.log("bottomViewId", this.data.bottomViewId)
  }

});